import { defineComponent } from "vue";
import { onMounted, onUnmounted, ref, watch, nextTick } from "vue";
import * as echarts from "echarts";
import "echarts-wordcloud";
import { EChartsType, Payload } from "echarts";
import { debounce } from "lodash-es";
import macarons from "../themes/macarons";
import { chartsProps } from "./charts-types";
echarts.registerTheme("default", macarons);
const themes = {
  default: macarons,
};
export default defineComponent({
  name: "TitanCharts",
  inheritAttrs: false,
  props: chartsProps,
  setup(props, { expose, emit, attrs }) {
    const chartsRef = ref<HTMLElement>();

    // 定义chart
    let charts: EChartsType | undefined = undefined;

    const getTheme = () => {
      return themes[props.theme as keyof typeof themes];
    };

    const dispatchActionEvent = (options: Payload) => {
      charts && charts.dispatchAction(options);
    };

    expose({
      themes,
      echarts,
      getTheme,
      dispatchActionEvent,
    });

    // const emit = defineEmits<{
    //   (e: "click", value: any): void;
    // }>();

    /**
     * 当options变化得时候 重新set
     */
    watch(
      () => props.options,
      async () => {
        await nextTick();
        if (!charts) {
          await initCharts();
        }

        props.options && charts && charts.setOption(props.options);
      }
    );

    const handleResize = () => {
      charts && charts.resize();
    };
    const handleResizeDebounce = debounce(function () {
      handleResize();
    }, 400);

    const initCharts = async () => {
      await nextTick();
      charts && charts.dispose();
      if (chartsRef.value) {
        charts = echarts.init(chartsRef.value, themes[props.theme as keyof typeof themes] || macarons);
      }
      const listeners = Object.keys(attrs)
        .filter((key) => key.includes("on"))
        .map((item) => item.replace("on", ""));
      listeners.forEach((key) => {
        const _event = key.toLowerCase();
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        charts?.off(_event).on(_event, (e: any) => attrs["on" + key](e) as any);
      });
    };

    const disposeCharts = () => {
      charts && charts.dispose();
      window.removeEventListener("resize", handleResizeDebounce);
    };

    onMounted(async () => {
      await initCharts();
      window.addEventListener("resize", handleResizeDebounce);
      if (props.options) {
        charts && charts.setOption(props.options);
      }
    });

    onUnmounted(() => {
      disposeCharts();
    });

    return () => {
      return (
        <div
          ref={chartsRef}
          class="titan-charts w-h-100"
        />
      );
    };
  },
});
